<?php

class Application_Model_BoxMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Box');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Box $box)
	{
		$data = array(
				'id' => $box->getId(),
				'longititude' => $box->getLongitude(),
				'latitude' => $box->getLatitude(),
				'online' => $box->getOnline(),
				'error_code' => $box->getErrorCode(),
				'areaid' => $box->getAreaId(),
				//'created' => date('Y-m-d H:i:s'),
		);
	
		if (null === ($id = $box->getId())) {
			unset($data['id']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
	
	public function find($id)
	{
		$box = new Application_Model_Box();
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$box->setId($row->id)
		->setLongitude($row->longitude)
		->setLatitude($row->latitude)
		->setOnline($row->online)
		->setErrorCode($row->error_code)
		->setAreaId($row->areaid)

		;
		return $box;
	}
	
	public function findByAreaId($areaid){
		$entries   = array();
		
		$table = $this->getDbTable();
		$db = $table->getAdapter();
		$where = $db->quoteInto('areaid = ?', $areaid);
		$resultSet = $table->fetchAll($where);
		
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Box();
			$entry->setId($row->id)
			->setLongitude($row->longitude)
			->setLatitude($row->latitude)
			->setOnline($row->online)
			->setErrorCode($row->error_code)
			->setAreaId($row->areaid)
			;
			$entries[] = $entry;
		}
		
		return $entries;
	}
	
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Box();
			$entry->setId($row->id)
			->setLongitude($row->longitude)
			->setLatitude($row->latitude)
			->setOnline($row->online)
			->setErrorCode($row->error_code)
			->setAreaId($row->areaid);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function searchRadius($longitude, $latitude, $radius){
		//search according to longitude and latitude and radius
		//return array of model Box
		
	}
	
	

}

